package com.rzn.reading.controller;


import com.rzn.reading.BusinessException;
import com.rzn.reading.JsonResult;
import com.rzn.reading.Message;
import com.rzn.reading.model.dto.AttachResultDTO;
import com.rzn.reading.model.param.UploadParam;
import com.rzn.reading.service.AttachService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 附件表 前端控制器
 * </p>
 *
 * @author rzn
 * @since 2022-02-12
 */
@RestController
@RequestMapping("//attach")
@Api(tags = "文件")
public class AttachController {
    private final AttachService attachService;

    public AttachController(AttachService attachService) {
        this.attachService = attachService;
    }

    @ApiOperation("/单文件上传")
    @PostMapping("/upload/{ownerName}/{ownerId}/{category}")
    public JsonResult upload(MultipartFile file,
                             @PathVariable("ownerName") String ownerName,
                             @PathVariable("ownerId") Integer ownerId,
                             @PathVariable("category") String category) throws IOException {
        AttachResultDTO upload = attachService.upload(file,ownerName,ownerId,category);
        return JsonResult.success(upload);
    }

    @ApiOperation("/多文件上传")
    @PostMapping("/uploadBatch")
    public JsonResult uploadBatch(MultipartFile[] files) {
        List<AttachResultDTO> attachResultDTOS = attachService.uploadBatch(files);
        return JsonResult.success(attachResultDTOS);
    }

    @ApiOperation("获取包的地址")
    @GetMapping("/download")
    public JsonResult download(@RequestParam("ownerName") String ownerName,
                               @RequestParam("ownerId")Integer ownerId) {
        List<String> urls = attachService.getUrls(ownerName, ownerId);
        return JsonResult.success(urls);
    }

    @ApiOperation("删除文件")
    @DeleteMapping("/removeById")
    public JsonResult removeById(Integer id) {
        boolean removed = attachService.removeById(id);
        if(!removed) {
            throw new BusinessException(new Message("DB.DELETE_FAILED","文件"));
        }
        return JsonResult.success(new Message("DB.DELETE_SUCCESS","文件"));
    }
}

